package com.zlzlib.librxoknet.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Enumeration;

/**
 * Created by zlz on 2017/10/24.
 */

public class NetWorkUtils {


    /**
     * 网络类型状态
     * android.permission.ACCESS_NETWORK_STATE
     *
     * @param context
     * @return 返回值 -1：没有网络  1：WIFI网络2：wap网络3：net网络
     */
    public static int getNetType(Context context) {
        int netType = -1;
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        @SuppressLint("MissingPermission") NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            if (networkInfo.getExtraInfo().toLowerCase().equals("cmnet")) {
                netType = 3;
            } else {
                netType = 2;
            }
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 1;
        }
        return netType;
    }

    /*
     * 判断网络连接是否已开  true 已打开 false 未打开
     *   android.permission.ACCESS_NETWORK_STATE
     */
    @SuppressLint("MissingPermission")
    public static boolean isHasNet(Context context) {
        try {
            if (context != null) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
                if (mNetworkInfo != null) {
                    return mNetworkInfo.isConnectedOrConnecting();
                }
            }
        } catch (Exception e) {
        }
        return false;
    }

    public enum ProviderName {
        chinaMobile("中国移动"), chinaUnicom("中国联通"), chinaTelecom("中国电信"), chinaNetcom("中国网通"), other("未知");
        private String text;

        ProviderName(String text) {
            this.text = text;
        }

        public String getText() {
            return this.text;
        }
    }

    /**
     * 获取SIM卡的IMSI码 SIM卡唯一标识：IMSI 国际移动用户识别码 （IMSI：International Mobile
     * Subscriber Identification Number）是区别移动用户的标志， 储存在SIM卡中，可用于区别移动用户的有效信息。
     * IMSI由MCC、MNC、MSIN组成，其中MCC为移动国家号码，由3位数字组成，
     * 唯一地识别移动客户所属的国家，我国为460；MNC为网络id，由2位数字组成， 用于识别移动客户所归属的移动网络，中国移动为00，中国联通为01,
     * 中国电信为03；MSIN为移动客户识别码，采用等长11位数字构成。 唯一地识别国内GSM移动通信网中移动客户。
     * 所以要区分是移动还是联通，只需取得SIM卡中的MNC字段即可
     */
    public static ProviderName getProviderName(Context context) {
        String imsi = getIMSI(context);
        if (imsi != null) {
            // 因为移动网络编号46000下的IMSI已经用完,所以虚拟了一个46002编号，134/159号段使用了此编号
            if (imsi.startsWith("46000") || imsi.startsWith("46002") || imsi.startsWith("46007")) {
                return ProviderName.chinaMobile;
            } else if (imsi.startsWith("46001")) {
                return ProviderName.chinaUnicom;
            } else if (imsi.startsWith("46003")) {
                return ProviderName.chinaTelecom;
            } else {
                return ProviderName.other;
            }
        } else {
            return ProviderName.other;
        }
    }

    /**
     * IMEI 全称为 International Mobile Equipment Identity，中文翻译为国际移动装备辨识码，
     * 即通常所说的手机序列号，
     * 用于在手机网络中识别每一部独立的手机，是国际上公认的手机标志序号，相当于移动电话的身份证。序列号共有15位数字，前6位（TAC）是型号核准号码，
     * 代表手机类型。接着2位（FAC）是最后装配号，代表产地。后6位（SNR）是串号，代表生产顺序号。最后1位（SP）一般为0，是检验码，备用。
     * 国际移动装备辨识码一般贴于机身背面与外包装上，同时也存在于手机记忆体中，通过输入*#06#即可查询。
     * android.permission.READ_PHONE_STATE
     *
     * @param context
     * @return
     */
    @SuppressLint("MissingPermission")
    public static String getIMEI(Context context) {
        String imei = "";
        try {
            TelephonyManager ts = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
                //Android 10 获取不到
                imei = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                imei = ts.getImei(0);
            } else {
                imei = ts.getDeviceId();
            }
        } catch (Exception e) {
        }
        if (imei == null) {
            imei = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        }
        return imei == null ? getDeviceSN() : imei;
    }


    public static String getDeviceSN() {
        String serialNumber = Build.SERIAL;
        return serialNumber;
    }


    /**
     * IMSI 全称为 International Mobile Subscriber
     * Identity，中文翻译为国际移动用户识别码。它是在公众陆地移动电话网
     * （PLMN）中用于唯一识别移动用户的一个号码。在GSM网络，这个号码通常被存放在SIM卡中
     * android.permission.READ_PHONE_STATE
     *
     * @param context
     * @return
     */
    @SuppressLint("MissingPermission")
    public static String getIMSI(Context context) {
        try {
            TelephonyManager ts = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            return ts.getSubscriberId();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 获取路由器Mac
     * android.permission.ACCESS_WIFI_STATE
     */
    @SuppressLint("MissingPermission")
    public static String getRouterMac(Context context) {
        try {
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            return wifi.getConnectionInfo().getBSSID();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 获取网卡MAC地址
     * android.permission.ACCESS_WIFI_STATE
     */
    public static String getAddressMAC(Context context) {
        try {
            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            @SuppressLint("MissingPermission") WifiInfo info = wifi.getConnectionInfo();
            return info.getMacAddress();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * WIFI网络开关
     * android.permission.CHANGE_WIFI_STATE
     */
    @SuppressLint("MissingPermission")
    public static Boolean toggleWiFi(Context context) {
        WifiManager wm = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        if (wm.isWifiEnabled()) {
            return true;
        } else {
            return wm.setWifiEnabled(true);
        }
    }


    /**
     * 将ip的整数形式转换成ip形式
     *
     * @param ipInt
     * @return
     */
    private static String int2ip(int ipInt) {
        StringBuilder sb = new StringBuilder();
        sb.append(ipInt & 0xFF).append(".");
        sb.append((ipInt >> 8) & 0xFF).append(".");
        sb.append((ipInt >> 16) & 0xFF).append(".");
        sb.append((ipInt >> 24) & 0xFF);
        return sb.toString();
    }

    /**
     * 获取wifi 下的ip地址
     * android.permission.ACCESS_WIFI_STATE
     *
     * @param context
     * @return
     */
    private static String getWifiIp(Context context) {
        try {
            WifiManager wifiManager = (WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);
            @SuppressLint("MissingPermission") WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int i = wifiInfo.getIpAddress();
            return int2ip(i);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * GPRS连接下的ip
     *
     * @return
     */
    private static String getGprsIp() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * android.permission.ACCESS_WIFI_STATE
     *
     * @param context
     * @return
     */
    public static String getWay(Context context) {
        WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        @SuppressLint("MissingPermission") DhcpInfo dhcpInfo = wifi.getDhcpInfo();
        return int2ip(dhcpInfo.gateway);
    }

    /**
     * 获得ip地址
     *
     * @param context
     * @return
     */
    public static String getLocalIp(Context context) {
        if (getNetType(context) == 1) {
            String ip = getWifiIp(context);
            if (!TextUtils.isEmpty(ip)) {
                return ip;
            }
        } else if (getNetType(context) == 2 || getNetType(context) == 3) {
            String ip = getGprsIp();
            if (!TextUtils.isEmpty(ip)) {
                return ip;
            }
        }
        return "0.0.0.0";
    }

    /**
     * @return 本地ip
     */
    public static String getLocalHostIp() {
        String ipAddress = "";
        try {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            // 遍历所用的网络接口
            while (en.hasMoreElements()) {
                NetworkInterface nif = en.nextElement();// 得到每一个网络接口绑定的所有ip
                Enumeration<InetAddress> inet = nif.getInetAddresses();
                // 遍历每一个接口绑定的所有ip
                while (inet.hasMoreElements()) {
                    InetAddress ip = inet.nextElement();
                    if (!ip.isLoopbackAddress() && ip instanceof Inet4Address) {
                        ipAddress = ip.getHostAddress();
                        break;
                    }
                    ip = null;
                }
                if (!ipAddress.isEmpty()) {
                    break;
                }
                nif = null;
                inet = null;
            }
            en = null;
        } catch (SocketException e) {
            ipAddress = "";// 为空将会返回获取主机ip失败的错误信息
        }
        return ipAddress;
    }

    /**
     * 获取服务器时间
     *
     * @param url
     * @return
     */
    public static long getNetWorkTime(String url) {
        URLConnection conn = null;
        try {
            URL url1 = new URL(url);
            conn = url1.openConnection();
            conn.setConnectTimeout(12000);
            conn.setReadTimeout(12000);
            conn.connect();
        } catch (Exception e) {
        }
        if (conn == null) {
            return System.currentTimeMillis();
        }
        return conn.getDate();
    }
}
